<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.EditPlan"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      @closed="closeDialog"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="120px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.ProgrammeName"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="dataList.Deviceremark" :error="errorMsg.remark">
          <el-input v-model="formData.remark" autocomplete="off"></el-input>
        </el-form-item>
        <br />
        <div class="base-content-operate" style="float: left">
          <el-button type="primary" @click="choiceDevice">{{
            dataList.SelectDevice
          }}</el-button>
          <el-button type="primary" @click="batchSetting">{{
            btn.BatchSetting
          }}</el-button>
          <el-button type="primary" @click="importData">{{
            btn.Import
          }}</el-button>
          <el-button type="danger" @click="deleteBatches">{{
            btn.BulkDelete
          }}</el-button>
          <el-input
            v-model="deviceNameNum"
            :placeholder="dataList.EnterContent"
            class="input-with-select"
            style="width: 200px; margin-left: 10px"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <br />
        <div style="width: 100%">
          <el-table
            ref="verificationTable"
            :key="bomCheckKey"
            :data="listData"
            element-loading-text="Loading"
            height="430"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column :label="dataList.DeviceNumber">
              <template slot-scope="scope">
                {{ scope.row.deviceDto.num }}
              </template>
            </el-table-column>
            <el-table-column
              :label="
                $i18n.locale === 'en'
                  ? dataList.DeviceEName
                  : dataList.DeviceName
              "
            >
              <template slot-scope="scope">
                {{ scope.row.deviceDto.name }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.DeviceSpecifications">
              <template slot-scope="scope">
                {{ scope.row.deviceDto.specifications }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.InspectionTarget">
              <template slot-scope="scope">
                {{ scope.row.verificationObject }}
              </template>
            </el-table-column>

            <el-table-column :label="dataList.InspectionMethod">
              <template slot-scope="scope">
                {{ scope.row.verificationWay }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.InspectionProcedure">
              <template slot-scope="scope">
                {{ scope.row.verificationMethod }}
              </template>
            </el-table-column>

            <el-table-column :label="dataList.Operation">
              <template slot-scope="scope">
                <div class="base-table-operation">
                  <el-link
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index)"
                    >{{ btn.Delete }}</el-link
                  >
                  <el-link
                    style="margin-left: 5px"
                    size="mini"
                    type="primary"
                    @click="setting(scope.row)"
                    >{{ btn.Setting }}</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit(1)">{{
          btn.Save
        }}</el-button>
        <el-button type="primary" style="width: 120px" @click="onSubmit(2)">{{
          btn.SaveAndSubmit
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
    <DeviceDialogList
      v-if="choiceDeviceVisible"
      :dialog-form-visible.sync="choiceDeviceVisible"
      :not-display-text.sync="notDisplayText"
      @checkedRowsFun="closeChoiceDevice"
    />
    <ImportComponents
      ref="ImportComponents"
      v-model="importVisible"
      @success="closeDialog"
      @UploadMethod="UploadMethod"
      @DownloadMethod="DownloadMethod"
    />
    <DeviceVerificationSettingDialog
      v-if="pitchSettingVisible"
      ref="DeviceVerificationPitchSettingDialog"
      :dialog-form-visible.sync="pitchSettingVisible"
      @settingDialogClose="settingDialogClose"
    />
    <DeviceVerificationSettingDialog
      v-if="settingVisible"
      ref="DeviceVerificationSettingDialog"
      :dialog-form-visible.sync="settingVisible"
      :verification-data="verificationData"
      @settingDialogClose="settingDialogClose"
    />
  </div>
</template>

<script>
import {
  getList,
  delAndUpdates,
  updateAndVerifyStart,
} from "../../../api/DeviceVerification";
import { DownloadVerificationTemplate } from "../../../api/DeviceImportComponents";
import DeviceDialogList from "../../../components/DeviceDialogList.vue";
import DeviceVerificationSettingDialog from "./DeviceVerificationSettingDialog.vue";
import { DeviceImport } from "../../../api/Device.js";
export default {
  name: "DeviceVerificationEditDialog",
  components: { DeviceDialogList, DeviceVerificationSettingDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      notDisplayText: [this.$t("ModuleDevice.Device.Scrap")],
      verificationData: {
        verificationWayList: [],
        verificationObjectList: [],
        verificationMethod: "",
      },
      rows: [],
      idList: [],
      bomCheckKey: 0,
      settingVisible: false,
      pitchSettingVisible: false,
      list: [],
      tableDatas: [],
      importVisible: false,
      choiceDeviceVisible: false,
      loading: false,
      innerDialogFormVisible: false,
      deviceNameNum: "",
      initData: {
        id: 0,
        num: "",
        name: "",
        status: 0,
        statusName: "",
        prepared: 0,
        preparedName: "",
        preparedDate: 0,
        remark: "",
      },
      formData: {
        id: 0,
        num: "",
        name: "",
        status: 0,
        statusName: "",
        prepared: 0,
        preparedName: "",
        preparedDate: 0,
        remark: "",
      },
      formDataRules: {
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        status: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        statusName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        prepared: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        preparedName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        preparedDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        name: "",
        status: "",
        statusName: "",
        prepared: "",
        preparedName: "",
        preparedDate: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        name: "",
        status: "",
        statusName: "",
        prepared: "",
        preparedName: "",
        preparedDate: "",
        remark: "",
      },
    };
  },
  computed: {
    listData() {
      return this.formData.deviceVerificationInfoDtoList.filter((record) => {
        return (
          record.deviceDto.num.includes(this.deviceNameNum) ||
          record.deviceDto.name.includes(this.deviceNameNum)
        );
      });
    },
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {},
  created() {
    this.getList();
  },
  methods: {
    getList() {
      getList({ id: this.id }, { pageIndex: 1, pageSize: 1 }).then((res) => {
        this.formData = res.data.dataList[0];
      });
    },
    // 批量删除
    deleteBatches() {
      var rows = this.$refs.verificationTable.selection;
      rows.map((row) => {
        var index = this.formData.deviceVerificationInfoDtoList.indexOf(row);
        this.formData.deviceVerificationInfoDtoList.splice(index, 1);
      });
    },
    setting(row) {
      this.rows = [];
      this.rows.push(row);
      this.verificationData.verificationWayList = row.verificationWayList
        ? row.verificationWayList
        : [];
      this.verificationData.verificationObjectList = row.verificationObjectList
        ? row.verificationObjectList
        : [];
      this.verificationData.verificationMethod = row.verificationMethod
        ? row.verificationMethod
        : "";
      this.settingVisible = true;
    },

    handleDelete(index) {
      this.formData.deviceVerificationInfoDtoList.splice(index, 1);
    },
    // 关闭批量设置
    settingDialogClose(data) {
      var verificationObjectArray = [];
      data.verificationObjectList.map((item) => {
        verificationObjectArray.push(item.value);
      });
      var verificationWayArray = [];
      data.verificationWayList.map((item) => {
        verificationWayArray.push(item.value);
      });
      var verificationMethod = data.verificationMethod;

      this.rows.map((item) => {
        item.verificationWayList = data.verificationWayList;
        item.verificationObjectList = data.verificationObjectList;
        item.verificationObject = verificationObjectArray.join(",");
        item.verificationWay = verificationWayArray.join(",");
        item.verificationMethod = verificationMethod;
      });

      this.$nextTick(() => {
        this.bomCheckKey++;
      });
      this.idList = [];
    },
    // 上传
    UploadMethod(formData, fileCount) {
      formData.append("module", 2);
      DeviceImport(formData).then((res) => {
        if (res.code === 200) {
          var index = this.formData.deviceVerificationInfoDtoList.length;
          for (let i = 0; i < res.data.length; i++) {
            var deviceIds = [];
            this.formData.deviceVerificationInfoDtoList.map((item) => {
              deviceIds.push(item.deviceId);
            });
            var row = {};
            row = res.data[i];
            row.index = index;
            if (deviceIds.indexOf(row.deviceId) < 0) {
              this.formData.deviceVerificationInfoDtoList.push(
                JSON.parse(JSON.stringify(row))
              );
            }
          }
          this.importVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 下载
    DownloadMethod: DownloadVerificationTemplate,
    // 关闭上传文件弹框

    // 导入
    importData() {
      this.importVisible = true;
    },
    // 批量设置
    batchSetting() {
      var rows = this.$refs.verificationTable.selection;
      if (rows === null || rows.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Message.SelectDevice"));
        return false;
      }
      this.rows = rows;
      this.pitchSettingVisible = true;
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
      this.idList = this.tableDatas.map((item) => item.id);
    },
    // 关闭选择设备弹框
    closeChoiceDevice(data) {
      var deviceIds = [];
      this.formData.deviceVerificationInfoDtoList.map((item) => {
        deviceIds.push(item.deviceId);
      });
      data.map((item) => {
        var obj = {};
        obj.id = item.id;
        obj.deviceId = item.id;
        obj.deviceDto = item;
        if (deviceIds.indexOf(item.id) < 0) {
          this.formData.deviceVerificationInfoDtoList.push(obj);
        }
      });
    },
    // 新增选择设备
    choiceDevice() {
      this.choiceDeviceVisible = true;
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit(type) {
      if (
        this.formData.deviceVerificationInfoDtoList === null ||
        this.formData.deviceVerificationInfoDtoList.length === 0
      ) {
        this.$message.warning(this.$t("ModuleDevice.Message.TableDataNull"));
        return false;
      }
      this.formData.deviceVerificationInfoCreateRequestList =
        this.formData.deviceVerificationInfoDtoList;
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (type === 1) {
            this.formData.status = "10";
            this.formData.statusName = this.dataList.PeddingSubmission;

            delAndUpdates(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            this.formData.status = "20";
            this.formData.statusName = this.dataList.UnderReview;
            updateAndVerifyStart(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("prepared", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("preparedName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("preparedDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
